package com.xunshangwang.pinhaohuo.ui.dialogs;

import android.app.Dialog;
import android.content.Context;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.entity.Shipping;
import com.xunshangwang.pinhaohuo.entity.Trace;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.tools.SPHelper;

import org.json.JSONObject;

import java.util.List;

import cz.msebera.android.httpclient.Header;
import tool.library.ToastTool;
import tool.library.adapter.BaseListAdapter;

/**
 * Created by xzp on 16/3/18.
 */
public class LogisticsDialog extends DialogFragment implements View.OnClickListener{
    private ListView mTraceList;
    private ProgressBar mProgress;
    private TextView mShipperTypeText,mTrackingNumberText;
    private TraceAdapter mAdapter;
    private String mId;
    public static final LogisticsDialog newDialog(String id){
        LogisticsDialog dialog=new LogisticsDialog();
        Bundle bundle=new Bundle();
        bundle.putString("id", id);
        dialog.setArguments(bundle);
        return dialog;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(getArguments()!=null){
            mId=getArguments().getString("id","0");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view=inflater.inflate(R.layout.dialog_logistics, container, false);
        //getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
//        WindowManager.LayoutParams params=getDialog().getWindow().getAttributes();
//        params.gravity= Gravity.FILL_HORIZONTAL;
        mTraceList= (ListView) view.findViewById(R.id.shipping_traces_list);
        mProgress= (ProgressBar) view.findViewById(R.id.logistics_progress);
        mProgress.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(inflater.getContext(),R.color.red), PorterDuff.Mode.SRC_IN);
        mShipperTypeText= (TextView) view.findViewById(R.id.shipper_type_text);
        mTrackingNumberText= (TextView) view.findViewById(R.id.tracking_number_text);
        view.findViewById(R.id.dismiss_btn).setOnClickListener(this);
        mAdapter=new TraceAdapter(getActivity());
        mTraceList.setAdapter(mAdapter);
        return view;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
//         super.onCreateDialog(savedInstanceState);
        Dialog dialog=new Dialog(getActivity(),R.style.logistics_dialog_style);
        dialog.setCanceledOnTouchOutside(true);
      //  dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT);
        //dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        return dialog;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mTraceList.setVisibility(View.GONE);
        mTrackingNumberText.setVisibility(View.GONE);
        mProgress.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View view) {
        this.dismiss();
    }

    @Override
    public void onStart() {
        super.onStart();
        int width= (int) (SPHelper.getIntValue(getContext(), SPHelper.SP_CONFIG, SPHelper.SCREEN_WIDTH_PIXELS)*0.9f);
        getDialog().getWindow().setLayout(width, WindowManager.LayoutParams.WRAP_CONTENT);
        JsonHttpHandler<Shipping> httpHandler=new JsonHttpHandler<Shipping>() {
            @Override
            public Shipping parseData(JSONObject object) throws Throwable {
                return JSON.parseObject(object.getString("shipping"),Shipping.class);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Shipping errorResponse) {
                super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
                dismiss();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Shipping response) {
                if(response!=null) {
                    mShipperTypeText.setText("("+response.getShipper()+")");
                    mTrackingNumberText.setText("运单号:  "+response.getTracking_number());
                    mAdapter.setList(response.getTraces());
                    mTrackingNumberText.setVisibility(View.VISIBLE);
                    mProgress.setVisibility(View.GONE);
                    mTraceList.setVisibility(View.VISIBLE);
                }else {
                    dismiss();
                    ToastTool.showToast("获取物流信息失败");
                }
            }
        };
        httpHandler.setTag(getView());
        HttpTool.get(getContext(),"?g=Api&m=Project&a=express&order_id="+mId,httpHandler);
    }

    @Override
    public void onStop() {
        super.onStop();
        HttpTool.cancelRequests(getView());
    }
    private class TraceAdapter extends BaseListAdapter<Trace>{
        public TraceAdapter(Context context) {
            super(context);
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder holder;
            if(view==null){
                view=LayoutInflater.from(getContext()).inflate(R.layout.trace_item,viewGroup,false);
                holder=new ViewHolder();
                holder.timeText= (TextView) view.findViewById(R.id.trace_time_text);
                holder.remarkText= (TextView) view.findViewById(R.id.trace_remark_text);
                view.setTag(holder);
            }else {
                holder= (ViewHolder) view.getTag();
            }
            Trace trace=getList().get(i);
            holder.remarkText.setText(trace.getRemark());
            holder.timeText.setText(trace.getTime());
            return view;
        }
        class ViewHolder{
            private TextView timeText,remarkText;
        }
    }
}
